import re
from ipaddress import IPv4Address, IPv6Address

from app.libs.regexp import IP_RE, IPV6_RE


def is_ipv4(ip: str):
    """
    判断IP是否为内网IP
    from http://nodejs.cn/api/dns.html#dns_dns_lookup_hostname_options_callback
      https://zh.wikipedia.org/wiki/%E4%B8%93%E7%94%A8%E7%BD%91%E7%BB%9C

    ipv4 私有网段:
        10.0.0.0 - 10.255.255.255
        172.16.0.0 - 172.31.255.255
        192.168.0.0 - 192.168.255.255
        127.0.0.0 - 127.255.255.255

    ipv6 私有网段 ::
        ::1
        fc00:: - fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff
        fe80:: - febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff
        ff00:: - ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff

    ipv6转ipv4的网段
        ::ffff:0:0 - ::ffff:ffff:ffff【后两段】
        64:ff9b:: - 64:ff9b::ffff:ffff
        2002:: - 2002:ffff:ffff:ffff:ffff:ffff:ffff:ffff 【第二三段】
    Args:
        ip (str): [description]

    Returns:
        bool: [description]
    """
    bits = ip.split('.')
    flag = [True] * 4 == [(True) if (x.isdigit() and 0 <=
                                     int(x) <= 255) else (False) for x in bits]

    if flag:
        a, b, c, d = [int(b) for b in bits]
        if a in (0, 10, 127) \
                or (a == 172 and 16 <= b <= 31) \
                or (a == 192 and b == 168):
            return False, 'IP是保留地址'
        else:
            return True, ''
    else:
        return False, 'IP地址不合法'


def check_source_ip(source_ip):
    if not source_ip:
        return False, "IP不能为空"
    if re.match(IP_RE, source_ip):
        ip = IPv4Address(source_ip)
    elif re.match(IPV6_RE, source_ip):
        ip = IPv6Address(source_ip)
    else:
        return False, "IP不合法"
    if ip.is_private:
        return False, "IP不能为私有地址"

    return True, ip.exploded
